package com.exercise.widgets.textview

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatTextView
import com.exercise.widgets.R

class RequiredTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
    private val defaultSymbolText = "*"

    private var mShowSymbol: Boolean
    private var mSymbolText: String
    private var mSymbolTextColor: Int
    private var mText: String

    init {
        context.obtainStyledAttributes(attrs, R.styleable.RequiredTextView).run {
            mShowSymbol = getBoolean(R.styleable.RequiredTextView_showSymbol, false)
            mSymbolText = getString(R.styleable.RequiredTextView_symbolText) ?: defaultSymbolText
            mSymbolTextColor = getColor(R.styleable.RequiredTextView_symbolColor, Color.RED)
            mText = getString(R.styleable.RequiredTextView_android_text) ?: ""
            recycle()
        }
        setText(mText)
    }

    fun setText(text: String) {
        Log.d("RequiredTextView", "text: $text")

        val span = if (mShowSymbol) {
            SpannableString("$mSymbolText$text").apply {
                setSpan(
                    ForegroundColorSpan(mSymbolTextColor),
                    0,
                    mSymbolText.length,
                    SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        } else {
            SpannableString(text)
        }
        super.setText(span)
    }

}